package cn.wyu.blogrest;

/**
 * Created by ajinlong on 2021/10/25.
 */

import cn.wyu.blogrest.Exception.AuthException;
import cn.wyu.blogrest.entity.Auth;
import cn.wyu.blogrest.repository.AuthRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;


@Service
public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private AuthRepository authRepository;

    /**
     * 验证accessToken
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        super.preHandle(request,response,handler);

//        String accessToken = request.getParameter("accessToken");
        String accessToken = request.getHeader("accessToken");
//        String accessToken = null;
//        if(!request.getMethod().equals("OPTIONS")){
//           accessToken  = request.getHeader("accessToken");
//        }

        if(accessToken==null)
            throw new AuthException("accessToken is null");

        Auth auth  = this.authRepository.findFirstByAccessToken(accessToken);
        if(auth==null)
            throw new AuthException("Invalid accessToken");

        if(auth.getExpireTime().before(new Date()))
            throw new AuthException("accessToken expired");
        return true;
    }
}
